package com.ruoyi.common.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;

@Component
public class EncryptConfig {

    @Value("${encryt.key}")
    private String key;

    public String symmetricEncryt(String content) {
        return getCrypto().encryptBase64(content);
    }

    public String symmetricDecryp(String encryptData) {
        if (StrUtil.isBlank(encryptData)) {
            throw new AuthenticationServiceException("无效Token");
        }
        return getCrypto().decryptStr(encryptData);
    }

    private SymmetricCrypto getCrypto() {
        byte[] byteKey = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue(), key.getBytes()).getEncoded();
        SymmetricCrypto aes = SecureUtil.aes(byteKey);
        return aes;
    }
}
